import Vue from 'vue';
import Vuex from 'vuex';

Vue.use(Vuex);

import userApi from '@/api/user'

import storage from '@/utils/storage';

export default new Vuex.Store({
  state: {
    token: storage.getToken() ? storage.getToken() : '',
    userInfo: storage.getUserInfo() ? storage.getUserInfo() : '',
  },
  mutations: {
    saveToken(state,token){
      state.token = token
      storage.setToken(token)
    },
    saveUserInfo(state,userInfo){
      state.userInfo = userInfo,
      storage.setUserInfo(userInfo)
    }
  },
  actions: {
    doLogin({commit},data){
      return new Promise( async (resolve, reject)=>{
        let res = await userApi.doLogin(data.username, data.password)
        if(res.data.flag){
          let token = res.data.data.token
          commit('saveToken',token)
        }
        resolve(res)
      })
    },
    getUserInfo({commit}){
      return new Promise( async (resolve, reject)=>{
        let res = await userApi.getUserInfo()
        if(res.data.flag){
          let userInfo = res.data.data
          commit('saveUserInfo',userInfo)
        }
        resolve(res)
      })
    },
    getOut({commit}){
      return new Promise( async (resolve, reject)=>{
        let res = await userApi.getOut()
        if(res.data.flag){
          commit('saveToken', null)
          commit('saveUserInfo', null)
          storage.removeTandU();
        }
        resolve(res)
      })
    }
  },
  modules: {

  },
});
